package com.example.music_player

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.music_player.data.AppDatabase
import com.example.music_player.view.CircleImageView
import java.io.File
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class UserProfileActivity : AppCompatActivity() {
    private lateinit var ivAvatar: CircleImageView
    private lateinit var btnChangeAvatar: Button
    private lateinit var tvUsername: TextView
    private lateinit var btnChangeMusicFolder: Button
    private lateinit var btnLogout: Button
    private lateinit var tvCurrentFolder: TextView
    private lateinit var btnEditUsername: Button
    private lateinit var tvNickname: TextView
    private lateinit var rvPlayHistory: RecyclerView
    private lateinit var tvNoHistory: TextView
    private lateinit var playHistoryAdapter: PlayHistoryAdapter

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        if (permissions.all { it.value }) {
            // 权限获取成功，打开图片选择器
            openImagePicker()
        } else {
            Toast.makeText(this, "需要存储权限才能访问图片", Toast.LENGTH_LONG).show()
        }
    }

    private val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { selectedImageUri ->
            try {
                // 复制图片到应用私有目录
                val avatarFile = saveAvatarToInternalStorage(selectedImageUri)
                // 立即刷新头像显示
                refreshAvatar(avatarFile)
                // 保存头像路径
                saveAvatarPath(avatarFile.absolutePath)
            } catch (e: Exception) {
                Toast.makeText(this, "更换头像失败", Toast.LENGTH_SHORT).show()
                e.printStackTrace()
            }
        }
    }

    private val folderPickerLauncher = registerForActivityResult(
        ActivityResultContracts.OpenDocumentTree()
    ) { uri: Uri? ->
        uri?.let {
            val currentUsername = getCurrentUsername()
            saveFolderPath(it, currentUsername)
            tvCurrentFolder.text = "当前音乐文件夹：${it.path}"
            Toast.makeText(this, "音乐文件夹已更新，重启应用后生效", Toast.LENGTH_LONG).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_profile)

        ivAvatar = findViewById(R.id.iv_avatar)
        btnChangeAvatar = findViewById(R.id.btn_change_avatar)
        tvUsername = findViewById(R.id.tv_username)
        btnChangeMusicFolder = findViewById(R.id.btn_change_music_folder)
        btnLogout = findViewById(R.id.btn_logout)
        tvCurrentFolder = findViewById(R.id.tv_current_folder)
        btnEditUsername = findViewById(R.id.btn_edit_username)
        tvNickname = findViewById(R.id.tv_nickname)
        rvPlayHistory = findViewById(R.id.rv_play_history)
        tvNoHistory = findViewById(R.id.tv_no_history)
        
        // 设置RecyclerView
        rvPlayHistory.layoutManager = LinearLayoutManager(this)
        playHistoryAdapter = PlayHistoryAdapter(emptyList())
        rvPlayHistory.adapter = playHistoryAdapter

        // 显示当前用户名和昵称
        val currentUsername = getCurrentUsername()
        tvUsername.text = "用户名：$currentUsername"
        
        // 加载并显示昵称
        CoroutineScope(Dispatchers.IO).launch {
            val userDao = AppDatabase.getDatabase(this@UserProfileActivity).userDao()
            val user = userDao.getUserByUsername(currentUsername)
            withContext(Dispatchers.Main) {
                tvNickname.text = "昵称：${user?.nickname ?: ""}"
            }
        }

        // 加载保存的头像
        loadSavedAvatar()

        // 显示当前音乐文件夹
        updateCurrentFolderDisplay()

        // 加载播放记录
        loadPlayHistory()

        // 更换头像按钮
        btnChangeAvatar.setOnClickListener {
            checkAndRequestPermissions()
        }

        // 更改音乐文件夹按钮
        btnChangeMusicFolder.setOnClickListener {
            folderPickerLauncher.launch(null)
        }

        // 退出登录按钮
        btnLogout.setOnClickListener {
            // 清除当前用户信息
            getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
                .edit()
                .remove("currentUsername")
                .apply()

            // 返回登录界面
            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
            finish()
        }

        btnEditUsername.setOnClickListener {
            showEditUsernameDialog()
        }
    }

    private fun checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上使用新的权限
            if (checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) 
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(arrayOf(
                    android.Manifest.permission.READ_MEDIA_IMAGES
                ))
            } else {
                openImagePicker()
            }
        } else {
            // Android 12 及以下使用旧的存储权限
            if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(arrayOf(
                    android.Manifest.permission.READ_EXTERNAL_STORAGE
                ))
            } else {
                openImagePicker()
            }
        }
    }

    private fun openImagePicker() {
        pickImage.launch("image/*")
    }

    private fun saveAvatarToInternalStorage(uri: Uri): File {
        val inputStream = contentResolver.openInputStream(uri)
        val avatarFile = File(getAvatarDirectory(), "${getCurrentUsername()}_avatar")
        
        inputStream?.use { input ->
            avatarFile.outputStream().use { output ->
                input.copyTo(output)
            }
        }
        
        return avatarFile
    }

    private fun getAvatarDirectory(): File {
        val avatarDir = File(filesDir, "avatars")
        if (!avatarDir.exists()) {
            avatarDir.mkdirs()
        }
        return avatarDir
    }

    private fun saveAvatarPath(path: String) {
        getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .edit()
            .putString("avatar_${getCurrentUsername()}", path)
            .apply()
    }

    private fun loadSavedAvatar() {
        val avatarPath = getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .getString("avatar_${getCurrentUsername()}", null)
        
        if (avatarPath != null) {
            val avatarFile = File(avatarPath)
            if (avatarFile.exists()) {
                refreshAvatar(avatarFile)
            }
        }
    }

    private fun getCurrentUsername(): String {
        return getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .getString("currentUsername", "defaultUser") ?: "defaultUser"
    }

    private fun getCurrentMusicFolder(username: String): String? {
        return getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .getString("lastFolderPath_$username", null)
    }

    private fun saveFolderPath(uri: Uri, username: String) {
        try {
            // 先尝试获取权限
            contentResolver.takePersistableUriPermission(
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            )

            // 保存路径
            getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
                .edit()
                .putString("lastFolderPath_$username", uri.toString())
                .apply()

            // 立即更新显示
            updateCurrentFolderDisplay()

            // 发送广播通知 UserActivity 更新
            val intent = Intent("com.example.music_player.FOLDER_CHANGED")
            intent.setPackage(packageName)
            intent.putExtra("folder_uri", uri.toString())
            sendBroadcast(intent)

            Toast.makeText(this, "音乐文件夹已更新", Toast.LENGTH_SHORT).show()

        } catch (e: SecurityException) {
            Toast.makeText(this, "无法获取文件夹访问权限", Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshAvatar(avatarFile: File) {
        try {
            // 清除 ImageView 的缓存
            ivAvatar.setImageDrawable(null)
            // 使用新的 URI 设置图片
            ivAvatar.setImageURI(Uri.fromFile(avatarFile))
            // 强制重绘
            ivAvatar.invalidate()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun updateCurrentFolderDisplay() {
        val currentUsername = getCurrentUsername()
        val currentFolder = getCurrentMusicFolder(currentUsername)
        if (currentFolder != null) {
            try {
                val uri = Uri.parse(currentFolder)
                val path = getReadablePath(uri)
                tvCurrentFolder.text = "当前音乐文件夹：$path"
            } catch (e: Exception) {
                tvCurrentFolder.text = "当前音乐文件夹：默认"
            }
        } else {
            tvCurrentFolder.text = "当前音乐文件夹：默认"
        }
    }

    private fun getReadablePath(uri: Uri): String {
        return try {
            when {
                uri.path?.contains("primary:") == true -> {
                    uri.path?.replace("tree/primary:", "存储设备/") ?: "未知路径"
                }
                uri.path != null -> {
                    uri.path ?: "未知路径"
                }
                else -> "未知路径"
            }
        } catch (e: Exception) {
            "未知路径"
        }
    }

    // 在 onResume 中也更新显示，确保在返回此界面时显示正确
    override fun onResume() {
        super.onResume()
        updateCurrentFolderDisplay()
    }

    /**
     * 显示修改昵称的对话框
     */
    private fun showEditUsernameDialog() {
        val editText = EditText(this).apply {
            // 获取前昵称
            CoroutineScope(Dispatchers.IO).launch {
                val userDao = AppDatabase.getDatabase(this@UserProfileActivity).userDao()
                val user = userDao.getUserByUsername(getCurrentUsername())
                withContext(Dispatchers.Main) {
                    setText(user?.nickname ?: "")
                }
            }
            setSingleLine()
        }

        AlertDialog.Builder(this)
            .setTitle("修改昵称")
            .setView(editText)
            .setPositiveButton("确定") { dialog, _ ->
                val newNickname = editText.text.toString().trim()
                if (newNickname.isEmpty()) {
                    Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }
                updateNickname(newNickname)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 更新昵称
     * @param newNickname 新的昵称
     */
    private fun updateNickname(newNickname: String) {
        val username = getCurrentUsername()
        
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val userDao = AppDatabase.getDatabase(this@UserProfileActivity).userDao()
                userDao.updateNickname(username, newNickname)

                withContext(Dispatchers.Main) {
                    tvNickname.text = "昵称：$newNickname"
                    Toast.makeText(this@UserProfileActivity, "昵称修改成功", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@UserProfileActivity, "修改失败：${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun loadPlayHistory() {
        val username = getCurrentUsername()
        CoroutineScope(Dispatchers.IO).launch {
            val historyDao = AppDatabase.getDatabase(this@UserProfileActivity).playHistoryDao()
            val history = historyDao.getUserHistory(username)
            
            withContext(Dispatchers.Main) {
                if (history.isEmpty()) {
                    tvNoHistory.visibility = View.VISIBLE
                    rvPlayHistory.visibility = View.GONE
                } else {
                    tvNoHistory.visibility = View.GONE
                    rvPlayHistory.visibility = View.VISIBLE
                    playHistoryAdapter.updateData(history)
                }
            }
        }
    }
}
